/**
 * Copyright [2015] Tianfu Ma (matianfu@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * File: main.c
 *
 * Created on: Jun 5, 2015
 * Author: Tianfu Ma (matianfu@gmail.com)
 */

#include <stdio.h>
#include <stdlib.h>
#include "../include/data_type.h"
#include "../include/alloc.h"
#include "../include/list.h"
#include "../include/attrlist.h"
#include "alloc_init.h"
#include "cube_buddy.h"


void open_file(char *, int);
int mem_display(unsigned char *, unsigned int);
int main() {

    int i;
    unsigned char * alloc_buffer;
    alloc_buffer=malloc(4096*(256+1));
    if((UINT64)alloc_buffer%4096==0)
        alloc_init(alloc_buffer,256);
    else
        alloc_init(alloc_buffer+4096-(UINT64)alloc_buffer%4096,256);
    BYTE * addr1;
    BYTE * addr2;


    addr1 = Calloc(10);
    addr2 = Calloc(10);
	Free0(addr1);
	Free0(addr2);
    free(alloc_buffer);
    return 0;
}

void open_file(char * str, int flag){
    FILE * pFile;
    pFile = fopen("./memdata.bin", "a+"); 
    if(pFile == NULL){
        printf("File cannot be opened/n");
    }

    switch (flag)
    {
    case 1:
        fputs(str, pFile);
        break;
    case 2:
        fprintf(pFile, "%p:\t", str);
        break;
    case 3:
        fprintf(pFile, "%02x ", str);
        break;
    default:
        break;
    }

    if (fclose(pFile) != 0) {
        printf("Error in closing file\n");
    }   
}

int mem_display(unsigned char *root_addr, unsigned int size){
    int i;
    unsigned char ch;
    unsigned char *temp;

    temp = root_addr;

 //   printf("%p:\t", temp);
    open_file(temp, 2);

    for(i = 1; i <= size; i++){
        ch = *temp;
//        printf("%02x  ", ch);
        open_file(ch, 3);
        temp++;
        if( !( i % 16 ) ){
 //           printf("\n");
            open_file("\n", 1);
            if(i != size){
   //             printf("%p:\t", temp);
                open_file(temp, 2);
            }
        }
    }

    open_file("\n", 1);
    return 0;
}
